<?php

namespace mpend\modules\h5\models;

use Yii;
use yii\filters\RateLimitInterface;
use common\models\user\UserAccountOrange;
use common\models\user\UserFollower;

/**
 * User model
 */
class User extends \common\models\BaseUser implements RateLimitInterface {

    public $token;

    // 返回在单位时间内允许的请求的最大数目，例如，[10, 60] 表示在60秒内最多请求10次。
    public function getAllowance() {
        return Yii::$app->cache->get($this->id . '_allowance');
    }

    public function getAllowanceUpdatedAt() {
        return Yii::$app->cache->get($this->id . '_allowance_updated_at');
    }

    // 返回在单位时间内允许的请求的最大数目，例如，[10, 60] 表示在60秒内最多请求10次。
    public function getRateLimit($request, $action) {
        return [3, 2];
    }

    // 返回剩余的允许的请求数。
    public function loadAllowance($request, $action) {
        return [$this->allowance, $this->allowanceUpdatedAt];
    }

    // 保存请求时的UNIX时间戳。
    public function saveAllowance($request, $action, $allowance, $timestamp) {
        Yii::$app->cache->set($this->id . '_allowance', $allowance);
        Yii::$app->cache->set($this->id . '_allowance_updated_at', $timestamp);
    }

    public function getOrange() {
        return $this->hasOne(UserAccountOrange::className(), ['user_id' => 'id']);
    }

    public function getTsline() {
        return false;
    }

    public function getUserFollower() {
        return $this->hasMany(UserFollower::className(), ['user_id' => 'id']);
    }

    public function fields() {
        return [
            'id',
            'username',
            'mobile' => function () {
                return ($this->meta && $this->meta->mobile) ? true : null;
            },
            'portrait' => function () {
                return $this->meta ? $this->meta->avatar : '';
            },
            'avatar' => function () {
                return $this->meta ? $this->meta->avatar : '';
            },
            'cover' => function () {
                return $this->meta ? $this->meta->cover : '';
            },
            'tsline',
            'followed',
        ];
    }

}
